<template>
  <div class="form-layout">
    <!--左侧导航-->
    <div class="nav-left">
      <customAnchor
        :itemList="[
          { name: 'box-base', title: '基础信息' },
          { name: 'box-dtl', title: '调价明细' },
        ]"
      />
    </div>

    <!--表单区域-->
    <div class="form-right" ref="formRight">
      <div id="box-base" class="box-title">基础信息</div>
      <customForm :data="form" :rules="propRules" ref="editForm" :disabled="propReadonly">
        <template #content>
          <customFormItem
            label="调价单号" name="adjustKey" :parent="_self" :form="form"
            disabled
            :config="{defaultValue: '自动获取'}"
          />
          <customFormItem
            label="调价时间" name="adjustDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
            :config="{'enable-time-picker': true}"
            disabled
          />
          <customFormItem
            label="调价类型" name="adjustType" :parent="_self" :form="form"
            disabled
            :type="constCommon.formItemType.selectDict.name"
            :config="{ dictType: constCommon.dictType.adjustType }"
          />
          <customFormItem
            label="调价人" name="adjustUser" :parent="_self" :form="form"
          />
          <customFormItem
            label="生效日期" name="effectiveDate" :parent="_self" :form="form"
            :type="constCommon.formItemType.datePicker.name"
            help="可以指定生效日期，仅提交调价单，当生效日期到了会自动审核并调价"
          />
          <customFormItem
            label="备注" name="remark" :parent="_self" :form="form"
          />
        </template>
      </customForm>

      <div id="box-dtl" class="box-title">调价明细</div>
      <data-view
        propViewKey="price_adjustment_item"
        propViewForm="price/adjustment-item/detail.vue"
        :propInitData="form"
        ref="childDataView"
        :propsDisableDbClick="true"
        :propAutoFetchData="false"
        @extra-button-click="extraButtonClick"
        :propHideFlowSelect="true"
        :propFlowKey="propParent.propFlowKey"
        :propNoEditRow="true"
        :propIsTdesign="true"
        :beforeButtonClickAsync="beforeButtonClickAsync"
        :propFilterBtn="propFilterBtn"
      />

       <!--影响库存-->
        <tableDrawer
          ref="affectStock"
          refName="affectStock"
          viewKey="price_adjust_stock"
          :queryWrapper="cpChildViewQueryWrapper"
          loadForce
          title="数据筛选条件:当前单据影响库存"
          :widthPer="80"
          :heightPx="-1"
          :widthPx="-1"
        />
    </div>

<!--    批量设置耗材价格-->
    <tableDrawer
      ref="tableDrawerBatch"
      loadForce
      refName="tableDrawerBatch"
      :queryWrapper="getMatrBatchQueryWrapper()"
      viewKey="base_matr_edit"
      title="批量设置商品价格"
      subtitle="选择商品、设置价格"
      :widthPx="-1"
      :heightPx="-1"
      attach="body"
      :widthPer="80"
      :propBeforeConfirm="tableDrawerBatchBeforeConfirm"
    >
      <template #contentTop>
        <customForm :data="formBatchData" :rules="formBatchRules" ref="formBatch" style="padding: 10px 0px">
          <template #content>
            <customFormItem
              label="调价后单品单价" name="skuPriceAfter" :parent="_self" :form="formBatchData" :type="constCommon.formItemType.inputNumber.name"
            />

            <customFormItem
              label="调价后HIS价格" name="hisPriceAfter" :parent="_self" :form="formBatchData" :type="constCommon.formItemType.inputNumber.name"
            />

            <customFormItem
              label="更新库存价格"
              name="flagStock"
              :parent="_self"
              :form="formBatchData"
              :type="constCommon.formItemType.switch.name"
              help="选中: 更新相关库存，未选中: 只更新耗材价格"
            />
            <customFormItem
              label="按耗材调整"
              name="flagMatr"
              :parent="_self"
              :form="formBatchData"
              help="选中: 按照耗材调整相关库存，未选中: 按照耗材及价格调整相关库存"
              :type="constCommon.formItemType.switch.name"
            />
          </template>
        </customForm>
      </template>
    </tableDrawer>
  </div>
</template>

<script>
import customAnchor from '@/components/custom/form/customAnchor.vue'

export default {
  data() {
    return {
      form: {},
      formBatchData: {
        skuPriceAfter: 0,
        hisPriceAfter: 0,
        flagStock: false,
        flagMatr: false
      },

      // 校验规则
      formBatchRules: {
        skuPriceNew: [{ required: true, message: '请输入', trigger: 'blur' }],
      }
    }
  },
  computed: {
    cpChildViewQueryWrapper() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('adjustId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      return queryWrapper
    },
  },
  methods: {
    //按钮事件
    async extraButtonClick({ button, data, index }) {
      let buttonKey = button.key
      if (buttonKey == 'get_stock') { //影响库存
        this.$refs.affectStock.show()
      }else if (buttonKey == 'matrBatch') { //批量设置
        this.$refs.tableDrawerBatch.show(null, true)
      }
    },
    // 加载明细数据
    loadDtl() {
      let queryWrapper = this.$newWrapper()
      if (this.form.id) {
        queryWrapper.eq('adjustId', this.form.id)
      } else {
        queryWrapper.ne(1, 1)
      }
      this.$refs.childDataView.setQueryWrapper(queryWrapper)
    },
    //按钮操作前
    async beforeButtonClickAsync(btn) {
      if(btn.code == 'vb-add'){ //添加前如果没保存，则先保存主表
        if (!this.form.id) {
          await this.propParent.ocAsynSaveViewForm()
          if (this.strings.isNotBlank(this.form.id)) {   //保存失败，排除服务器异常，则一般是校验失败
            this.$refs.childDataView.viewAdd()
          }
          return false
        }
      }
      return true
    },
    //按钮操作前
    tableDrawerBatchBeforeConfirm() {
      this.$refs.formBatch.validate().then((result) => {
        if (result && result == true) {
          let data = this.$refs.tableDrawerBatch.getData()
          if (data == null || data.length == 0) {
            this.utilMessage.warning('请选择商品')
            return
          }

          //主单据未保存
          if(this.propParent.cpFormNew) {
            this.propParent.ocAsynSaveViewForm(() => {
              this.setBatchSave(data)
            })
          } else {
            this.setBatchSave(data)
          }

        }
      })
      return false
    },
    getMatrBatchQueryWrapper() {
      let wrapper = this.$newWrapper()
      wrapper.ne('flag_disabled', 1)
      wrapper.ne('his_disabled', 1)
      wrapper.ne('hrp_finance_disabled', 1)
      wrapper.ne('hrp_disabled', 1)
      return wrapper
    },

    accAdd(arg1, arg2) {
      let r1
      let r2
      let m
      try {
        r1 = arg1.toString().split('.')[1].length
      } catch (e) {
        r1 = 0
      }
      try {
        r2 = arg2.toString().split('.')[1].length
      } catch (e) {
        r2 = 0
      }
      // eslint-disable-next-line no-restricted-properties
      m = Math.pow(10, Math.max(r1, r2))
      return ((arg1 * m - arg2 * m) / m).toFixed(2)
    },

    // 批量设置保存
    setBatchSave(data){
      this.utilVue.loadShow(true)
      let saveList = []
      data.forEach(row => {
        let rowNew = JSON.parse(JSON.stringify(row))
        rowNew.adjustId = this.form.id

        rowNew.matrId = rowNew.id
        rowNew.matrName = rowNew.name
        rowNew.matrSpec = rowNew.spec
        rowNew.matrModel = rowNew.model
        rowNew.hrpCodeBefore = rowNew.hrpCode
        rowNew.hrpCodeAfter = rowNew.hrpCode
        rowNew.skuPriceBefore = rowNew.skuPrice
        rowNew.hisPriceBefore = rowNew.hisPrice
        rowNew.hisCodeBefore = rowNew.hisCode
        rowNew.hisCodeAfter = rowNew.hisCode
        rowNew.skuPriceAfter = this.formBatchData.skuPriceAfter
        rowNew.hisPriceAfter = this.formBatchData.hisPriceAfter
        rowNew.flagStock = this.formBatchData.flagStock
        rowNew.flagMatr = this.formBatchData.flagMatr
        rowNew.hisPriceChange = this.accAdd(rowNew.hisPriceAfter, rowNew.hisPriceBefore)
        rowNew.skuPriceChange = this.accAdd(rowNew.skuPriceAfter, rowNew.skuPriceBefore)
        rowNew.id = null
        saveList.push(rowNew)
      })

      this.$ajax.post('/price/adjustment_item/saveBatch', saveList).then(resp => {
        this.utilVue.loadHide()
        if (resp.success) {
          this.$refs.tableDrawerBatch.hide()
          this.utilMessage.success(resp.msg)
          this.loadDtl()
        }
      })
    },

    // 过滤显示按钮
    propFilterBtn(btnList) {
      if (this.strings.defaultString(this.form.flowStatus, 'start') != 'start') {
        btnList =  btnList.filter(btn => !['matrBatch'].includes(btn.code))
      }
      if (this.strings.defaultString(this.form.flowStatus, 'start') != 'end') {
        btnList =  btnList.filter(btn => !['get_stock'].includes(btn.code))
      }
      return btnList
    }
  },
  created() {
    this.$emit('event-register', {
      validate: (callback) => {
        return this.$refs.editForm.validate(callback)
      },
      beforeSave: () => {
        this.$emit('data-callback', this.form)
        return true
      },
      afterMove: (formData, initData) => {
        this.form = global.utils.jsonClone(formData)
        if (!this.form.id) {
          // 新增
          this.$set(this.form, 'adjustType', '0')
          this.$set(this.form, 'adjustUser', this.utils.getCurrentUser().name)
          this.$set(this.form, 'adjustDate', new Date().format(this.dates.defaultDateTimePattern))
        }
        this.loadDtl()
      },
      afterSave: () => {
      },
      beforeDelete: () => {
        return true
      },
      afterDelete: () => {
      },
      beforeFlow: (flowButtonKey) => {
        return true
      },
      afterFlow: (flowButtonKey) => {
      },
      beforeClose: () => {
        return true
      }
    })
  },
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {
    customAnchor
  },
}
</script>
